package name.huzhenbo.java.objects;

class ImplementsValidEquals {

    private int number = 0;

    public ImplementsValidEquals(int number) {
        this.number = number;
    }

    public int getNumber() {
        return number;
    }

    @Override
    public boolean equals(Object obj) {
        // This will improve the performance when there's a large number of compares.
        if (this == obj) {
            return true;
        }
        if (obj instanceof ImplementsValidEquals) {
            return this.number == ((ImplementsValidEquals) obj).getNumber();
        }
        return false;
    }

    // When the object is put into a collection(hash based collection, like hashtable, hashmap, hashset), it first use hashCode to compute
    // the address where to store the object.
    // 1. If no object in the address, just put object there.
    // 2. If there's already an object there, compare use equals. If equals, ignore; otherwise, put in another place.
    // So: if 2 objects equals to each other, then the hashcode of them must be same. But same hashcode does not ensure equals.
    @Override
    public int hashCode() {
        return new Integer(number).hashCode();
    }

}
